package org.example2;

import org.springframework.boot.loader.archive.JarFileArchive;
import org.springframework.boot.loader.jar.Handler;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;

public class NestedJarReaderBySpringboot {
    /**
     * https://blog.csdn.net/mmake1994/article/details/142524929
     */
    public static void main(String args[]) throws Exception {
        System.out.println("------------------------------");
        String jarPath = System.getProperty("user.dir") + "/jarFileRear/jarFileDir/nestedJar.jar";
        getClassInfoByJarLib(jarPath);
    }

    public static void getClassInfoByJarLib(String jarPath) throws Exception {
        String filePath;
        String separator = File.separator;
        if("\\".equals(separator)){
            // windows系统使用如下路径
            filePath = "file:/"+ URLDecoder.decode(jarPath, "UTF-8").replaceAll("\\\\","/")+"!/";
        }else if("/".equals(separator)){
            // linux系统使用如下路径
            filePath = "file:"+ URLDecoder.decode(jarPath, "UTF-8").replaceAll("\\\\","/")+"!/";
        }else {
            throw new RuntimeException("未知操作系统，解析jarLib失败");
        }
        String rootJarPath = "jar:"+ filePath;
        try {
            JarFileArchive jarFileArchive = new JarFileArchive(new Handler().getRootJarFileFromUrl(new URL(rootJarPath)));
            //getNestedArchives获取嵌套的jar等文件，参数是个EntryFilter，过滤条件
            jarFileArchive.getNestedArchives(entry -> entry.getName().startsWith("org/example/") && entry.getName().endsWith(".jar"))
                    .forEach(archive -> {
                        archive.iterator().forEachRemaining(entry -> {
                            String entryName = entry.getName();
                            // 过滤嵌套jar包中字节码文件
                            if (entryName.endsWith(".class")) {
                                String className = entryName.replace('/', '.').replace(".class", "");
                                System.out.println("className:"+className);
                            }
                        });
                    });
        } catch (IOException e) {
            System.out.println("解析嵌套jarLib中ClassInfo异常，jarPath="+jarPath+"--------"+e);
            throw new RuntimeException(e);
        }
    }
}
